<template>
  <div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="visible"
      center
      :show-close="false"
      @close="$emit('close')"
      style="min-width: 635px"
    >
      <el-form
        ref="courseForm"
        :model="courseForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="学生姓名" prop="studentId">
          <el-input
            v-model="courseForm.studentName"
            placeholder="选择学生"
            @click.native="studentChooseDialogVisible = true"
          />
        </el-form-item>

        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="课程类型" prop="courseType">
              <el-select v-model="courseForm.courseType" placeholder="请选择课程类型">
                <el-option label="语法" value="语法"/>
                <el-option label="口语" value="口语"/>
                <el-option label="词汇" value="词汇"/>
                <el-option label="听力" value="听力"/>
                <el-option label="阅读" value="阅读"/>
                <el-option label="写作" value="写作"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程时长" prop="courseTimeType">
              <el-select
                v-model="courseForm.courseTimeType"
                placeholder="请选择课程时长"
                clearable
                class="duration-select"
                @change="handleDurationChange"
              >
                <el-option
                  v-for="(item, index) in durationOptions"
                  :key="index"
                  :value="item.id"
                  :label="item.name"
                >
                  <span style="float: left">{{ item.name }}</span>
                  <span class="time-badge">{{ item.duration }} 分钟</span>
                </el-option>
              </el-select>
              <div v-if="courseForm.selectedDuration" class="duration-tip">
                本课程消耗 {{ courseForm.selectedDuration.classHour }} 课时
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="courseForm.startTime"
                type="datetime"
                placeholder="选择开始时间"
                format="yyyy-MM-dd HH:mm"
                value-format="timestamp"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="courseForm.endTime"
                type="datetime"
                placeholder="选择结束时间"
                format="yyyy-MM-dd HH:mm"
                value-format="timestamp"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="上课地点" prop="location">
          <el-input v-model="courseForm.location" placeholder="请输入上课地点或线上会议信息"/>
        </el-form-item>

        <el-form-item label="课程备注">
          <el-input
            v-model="courseForm.notes"
            placeholder="请输入课程备注信息"
            type="textarea"
            rows="3"
          />
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="$emit('close')">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
    <student-choose-dialog v-model="studentChooseDialogVisible" @on-select="selectStudent"/>
  </div>
</template>

<script>
import StudentChooseDialog from '@/views/student/components/studentChooseDialog.vue'
import { courseDurationTypeList } from '@/api/wordSystemCourseDurationType'
import { createOrUpdateCourse } from '@/api/wordSystemCourse'

export default {
  name: 'AddEditCourseDialog',
  components: { StudentChooseDialog },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    course: {
      type: Object,
      default: null
    }
  },
  data() {
    // 验证结束时间必须大于开始时间
    const endTimeValidator = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择结束时间'))
      }
      if (this.courseForm.startTime && value <= this.courseForm.startTime) {
        return callback(new Error('结束时间必须晚于开始时间'))
      }
      callback()
    }
    return {
      // element-ui 日期选择器配置
      pickerOptions: {
        disabledDate(time) {
          // 禁用当前时间之前的所有时间
          return time.getTime() < Date.now()
        }
      },
      durationOptions: [],
      // 表单数据
      courseForm: {
        selectedDuration: null,
        studentId: '',
        studentName: '',
        courseType: '词汇',
        courseTimeType: '',
        startTime: '',
        endTime: '',
        location: '线上 腾讯会议',
        notes: ''
      },
      // 表单验证规则
      formRules: {
        studentId: [
          { required: true, message: '请输入学生姓名', trigger: 'change' }
        ],
        courseType: [
          { required: true, message: '请选择课程类型', trigger: 'change' }
        ],
        courseTimeType: [
          { required: true, message: '请选择课程时长类型', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' },
          { validator: endTimeValidator, trigger: 'change' }
        ],
        location: [
          { required: true, message: '请输入上课地点', trigger: 'blur' }
        ]
      },
      studentChooseDialogVisible: false
    }
  },
  computed: {
    // 对话框标题
    dialogTitle() {
      return this.course ? '编辑课程' : '新增课程'
    }
  },
  watch: {
    'courseForm.courseTimeType'(value) {
      this.courseForm.selectedDuration = this.durationOptions.find(item => item.id === value)
      this.handleDurationChange()
    },
    'courseForm.startTime'() {
      this.handleDurationChange()
    }
  },
  created() {
    // 获取课程类型
    this.loadDurationData()
    // 初始化表单数据
    if (this.course) {
      this.courseForm = {
        id: this.course.id,
        studentName: this.course.student,
        studentId: this.course.stuId,
        courseType: this.course.type,
        courseTimeType: this.course.courseDurationTypeId,
        startTime: this.course.startTime.getTime(),
        endTime: this.course.endTime.getTime(),
        location: this.course.location,
        notes: this.course.notes
      }
    } else {
      // 设置默认时间
      const now = new Date()
      const start = new Date(now.setHours(now.getHours() + 1, 0, 0, 0))
      this.courseForm.startTime = start.getTime()
    }
  },
  methods: {
    handleDurationChange() {
      if (!(this.courseForm.courseTimeType && this.courseForm.startTime)) {
        return
      }
      const change = this.durationOptions.filter(item => item.id === this.courseForm.courseTimeType)[0]
      if (change) {
        this.courseForm.endTime = this.courseForm.startTime + change.duration * 60 * 1000
      }
    },
    async loadDurationData() {
      this.durationOptions = await courseDurationTypeList({})
    },
    selectStudent(student) {
      this.studentSelect = student
      this.courseForm.studentName = student.name
      this.courseForm.studentId = student.id
      this.studentChooseDialogVisible = false
    },
    // 提交表单
    submitForm() {
      this.$refs.courseForm.validate(async valid => {
        if (valid) {
          // 转换时间戳为Date对象
          const formData = {
            courseDurationType: this.courseForm.courseTimeType,
            courseType: this.courseForm.courseType,
            startTimeTimestamp: this.courseForm.startTime,
            endTimeTimestamp: this.courseForm.endTime,
            location: this.courseForm.location,
            notes: this.courseForm.notes,
            stuId: this.courseForm.studentId,
            id: this.courseForm.id
          }
          const res = await createOrUpdateCourse(formData)
          if (res) {
            this.$emit('close')
          }
        }
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog {
  min-width: 700px;
}

.time-badge {
  float: right;
  color: #0084ff;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
}

.duration-tip {
  margin-top: 8px;
  line-height: 1.5;
  display: inline-block;
  padding: 3px 10px;
  background-color: #f0f7ff;
  color: #0084ff;
  border-radius: 15px;
  font-size: 12px;
  font-weight: 500;
}
</style>
